<template>
	<div>
		<div class="container">
			<h2 style="text-align: center;">采购管理</h2>
			<div class="toolbar">
				<a-form ref="searchRef" :model="searchState" @finish="current=1;loading=true;initData()">
					<a-row :gutter="20">
						<a-col :span="24">
							<a-form-item label="选择类型">
								<a-radio-group v-model:value="searchState.type" @change="doSearch">
									<a-radio-button v-for="option of typeOptions" :key="option.value" :value="option.value">{{ option.label }}</a-radio-button>
								</a-radio-group>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="20">
						<a-col :span="8">
							<a-form-item label="城市公司/专业公司">
								<a-select v-model:value="searchState.company_id" :show-search="true" placeholder="请选择城市公司/专业公司" :options="companyOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="选择项目">
								<a-select v-model:value="searchState.project_id" allow-clear :show-search="true" placeholder="请选择项目" :options="innerProjectOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="申请单号">
								<a-input v-model:value="searchState.code" placeholder="请输入" allow-clear></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="申请人">
								<a-input v-model:value="searchState.applier_name" placeholder="请输入" allow-clear></a-input>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="20">
						<a-col :span="12">
							<a-form-item label="时间范围">
								<a-range-picker v-model:value="searchState.date_range" allow-clear show-time value-format="YYYY-MM-DD HH:mm:ss" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item>
								<a-space>
									<a-button type="primary" html-type="submit">
										<search-outlined />搜索
									</a-button>
								</a-space>
							</a-form-item>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<div class="mt-2">
				<a-table :expanded-row-keys="expandedRowKeys" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="dataSource" :pagination="pagination" @expand="handleExpand" @change="initData">
					<template #bodyCell="{ column, record }">
						<template v-if="column.dataIndex === 'purchase_state'">
							<a-tag :color="record.purchase_Surplus_quantity > 0 ? 'processing' : 'default'">{{ record.purchase_Surplus_quantity > 0? '待采购': '已采购' }}</a-tag>
						</template>
						<template v-if="column.key === 'operation'">
							<a-space>
								<!-- <a-button type="link" @click="handleDetail(record)">
									<diff-outlined />查看
								</a-button>-->
								<a-button v-permission="58" type="link" @click="handleCreate(record)">
									<diff-outlined />查看
								</a-button>
							</a-space>
						</template>
					</template>
					<template #expandedRowRender="{record}">
						<a-table :columns="innerColumns" :data-source="record.materials" :pagination="false"></a-table>
					</template>
				</a-table>
			</div>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, computed, getCurrentInstance } from "vue";
import dayjs from "dayjs";
import { SearchOutlined, DiffOutlined } from "@ant-design/icons-vue";
import { post } from "../utils";
import router from "../router";
import { useRoute, useRouter } from "vue-router";
import { usePagination } from "vue-request";

const typeOptions = [
	{
		value: "purchase",
		label: "物资周转料采购"
	},
	{
		value: "shangtong",
		label: "商砼采购"
	},
	{
		value: "machineapply",
		label: "机械租赁"
	},
	{
		value: "auxiliary",
		label: "辅助物资采购"
	}
];

const searchRef = ref();
const searchState = reactive({
	type: typeOptions[0].value
});
const route = useRoute();
const query = route.query;
const expandedRowKeys = ref([]);
const handleExpand = (expanded, record) => {
	if (expanded) {
		expandedRowKeys.value.push(record.id);
	} else {
		const index = expandedRowKeys.value.findIndex(key => key === record.id);
		if (index > -1) {
			expandedRowKeys.value.splice(index, 1);
		}
	}
};

const columns = [
	{
		title: "序号",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left"
	},
	{
		title: "项目名称",
		dataIndex: "project",
		sorter: false,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text?.name;
		}
	},
	{
		title: "预约申请单号",
		dataIndex: "code",
		sorter: false,
		width: 150,
		ellipsis: true
	},
	{
		title: "申请人",
		dataIndex: "applier",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text.fullname || text.username;
		}
	},
	{
		title: "采购类型",
		dataIndex: "purchaseType",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			const typeItem = typeOptions.find(item => item.value === text);
			return typeItem.label;
		}
	},
	// {
	// 	title: "状态",
	// 	dataIndex: "status",
	// 	sorter: false,
	// 	width: 150,
	// 	ellipsis: true,
	// 	customRender: ({ text, record, index, column }) => {
	// 		return !status || status === 1 ? "待审核" : "未知";
	// 	}
	// },
	{
		title: "采购余量",
		dataIndex: "purchase_Surplus_quantity",
		sorter: false,
		width: 150,
		ellipsis: true
	},
	{
		title: "采购状态",
		dataIndex: "purchase_state",
		width: 100
	},
	{
		title: "创建时间",
		dataIndex: "create_time",
		sorter: false,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 120,
		align: "center"
	}
];

const purchaseColumns = [
	{
		title: "物资名称",
		dataIndex: "name",
		width: 200,
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		width: 150,
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		width: 130,
		align: "center"
	},
	{
		title: "数量",
		dataIndex: "quantity",
		width: 100,
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		width: 200,
		align: "center"
	}
];

const shangtongColumns = [
	{
		title: "工号",
		dataIndex: "part",
		customRender: ({ text, record, index, column }) => {
			return (record.gonghao?.name || "") + (record.partInfo?.name || "");
		}
	},
	{
		title: "预计浇筑部位",
		dataIndex: "expected_location",
		align: "center"
	},
	{
		title: "砼标号（类别）",
		dataIndex: "type"
	},
	{
		title: "预计浇筑方量（m3）",
		dataIndex: "fangliang",
		align: "center"
	},
	{
		title: "是否泵送（长度）",
		dataIndex: "changdu",
		align: "center"
	},
	{
		title: "申请塌落度（mm）",
		dataIndex: "luodu",
		align: "center"
	},
	{
		title: "现场联系人",
		dataIndex: "contacts",
		width: 200,
		align: "center"
	},
	{
		title: "现场联系电话",
		dataIndex: "tel",
		align: "center"
	},
	{
		title: "预计浇筑日期",
		dataIndex: "add_time",
		align: "center"
	}
];

const machineapplyColumns = [
	{
		title: "机械名称",
		dataIndex: "name",
		ellipsis: true
	},
	{
		title: "规格型号",
		dataIndex: "model",
		align: "center"
	},
	{
		title: "计量单位",
		dataIndex: "unit",
		align: "center"
	},
	{
		title: "数量",
		dataIndex: "quantity",
		align: "center"
	},
	{
		title: "使用时长",
		dataIndex: "use_time",
		align: "center"
	},
	{
		title: "时长单位",
		dataIndex: "time_unit",
		align: "center"
	},
	{
		title: "工作内容",
		dataIndex: "useFor",
		align: "center"
	},
	{
		title: "使用时间",
		dataIndex: "use_date",
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	}
];

const auxiliaryColumns = [
	{
		title: "物资名称",
		dataIndex: "name",
		ellipsis: true
	},
	{
		title: "规格型号",
		dataIndex: "model",
		align: "center"
	},
	{
		title: "计量单位",
		dataIndex: "unit",
		align: "center"
	},
	{
		title: "数量",
		dataIndex: "quantity",
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	}
];

const innerColumns = computed(() => {
	if (searchState.type === "purchase") {
		return purchaseColumns;
	} else if (searchState.type === "shangtong") {
		return shangtongColumns;
	} else if (searchState.type === "machineapply") {
		return machineapplyColumns;
	} else {
		return auxiliaryColumns;
	}
});
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));
const projectOptions = ref([]);
const companyOptions = ref([]);
const getProjects = async () => {
	const projectResult = await post("department/projects?type=3", { page_size: 1000 });
	projectOptions.value = projectResult.data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(',').map(item => parseInt(item)),
		};
	});
};
if (!projectOptions.value.length) {
	getProjects();
}

post("department/projects?type=2", {
	parent_ids: JSON.stringify([78, 24]),
}).then(({ data }) => {
	companyOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const innerProjectOptions = computed(() => {
	let options = [];
	if (!projectOptions.value.length) return options;
	if (searchState.company_id) {
		options = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		})
	} else {
		options = projectOptions.value;
	}
	if (!options.filter(item => item.value === searchState.project_id).length) {
		searchState.project_id = null;
	}
	return options;
})
const handleDetail = record => {
	router.push(`/${record.type}/info/${record.id}`);
};

const handleCreate = record => {
	router.push(`/purchase/order/create?planId=${record.id}&type=${record.purchaseType}`);
};

const pagination = ref({
	total: 0,
	current: 1,
	pageSize: 20
});
const proxy = getCurrentInstance();
const dataSource = ref([]);
const getDataSource = async () => {
	if (!searchState.type) {
		proxy.$message.error("请选择采购类型");
		return;
	}
	const query = {};
	if (pagination.value.pageSize) {
		query['page_size'] = pagination.value.pageSize;
	}
	if (pagination.value.current) {
		query['page'] = pagination.value.current;
	}
	router.replace({ query: {
		...query,
		...searchState,
		start_time: searchState.date_range && searchState.date_range[0],
		end_time: searchState.date_range && searchState.date_range[1],
		type: searchState.type
	}})
	const search = {};
	if (searchState.company_id) {
		if (!projectOptions.value.length) await getProjects();
		search.project_ids = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		}).map(item => item.value).join(',');
		if (!search.project_ids) {
			return [];
		}
	}
	post(searchState.type, {
		...searchState,
		...search,
		start_time: searchState.date_range && searchState.date_range[0],
		end_time: searchState.date_range && searchState.date_range[1],
		page: pagination.value.current,
		page_size: pagination.value.pageSize,
		workflow_status: 2,
		is_invalid: 0,
	}).then(({ data, total }) => {
		dataSource.value = (data || []).map(item => {
			item.applier = item.applier || item.purchaser;
			item.purchaseType = searchState.type;
			if (searchState.type === "purchase") {
				item.materials = (item.materials || []).map(item => {
					const { quantity, unit, memo } = item.PurchaseMaterial;
					return {
						...item,
						quantity,
						unit,
						memo
					};
				});
			} else if (searchState.type === "shangtong") {
				item.materials = [
					{
						...item,
						add_time: dayjs(item.add_time).format("YYYY-MM-DD HH:mm:ss")
					}
				];
			} else if (searchState.type === "machineapply") {
				item.materials = (item.materials || []).map(item => {
					const { quantity, unit, memo, time_unit, use_time, useFor, use_date } = item.MachineapplyMaterial;
					return {
						...item,
						quantity,
						unit,
						memo,
						time_unit,
						use_time,
						useFor,
						use_date: use_date ? dayjs(use_date).format("YYYY-MM-DD HH:mm:ss") : ""
					};
				});
			} else if (searchState.type === "auxiliary") {
				item.materials = (item.materials || []).map(item => {
					const { quantity, unit, memo } = item.AuxiliaryMaterial;
					return {
						...item,
						quantity,
						unit,
						memo,
					};
				})
			}
			return item;
		});
		pagination.value.total = total;
	});
};

const initData = (pag, filters, sorter) => {
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
		pagination.value.pageSize = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
		pagination.value.current = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters
	}})
	getDataSource()
};
if (query) {
	if (query.type) searchState.type = query.type;
	if (query.company_id) searchState.company_id = parseInt(query.company_id);
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.code) searchState.code = query.code;
	if (query.applier_name) searchState.applier_name = query.applier_name;
	if (query.start_time && query.end_time) {
		searchState.date_range = [
			dayjs(query.start_time).format('YYYY-MM-DD HH:mm:ss'),
			dayjs(query.end_time).format('YYYY-MM-DD HH:mm:ss')
		];
	}
	const pag = {};
	if (query.page_size) {
		pagination.value.pageSize = parseInt(query.page_size);
	}
	if (query.page) {
		pagination.value.current = parseInt(query.page);
	}
	initData(pag);
}

const doSearch = () => {
	pagination.value.current = 1;
	getDataSource();
};

const handleChange = pg => {
	pagination.value.current = pg.current;
	pagination.value.pageSize = pg.pageSize;
	getDataSource();
};
doSearch();
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
</style>
